﻿using DTOs;
using OA.IBLL;
using OA.WebAPI.App_Start;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace OA.WebAPI.Controllers
{
    public class AccountController : ApiController
    {
        public ISysPersonService PersonService { get; set; }

        [AllowAnonymous]
        [HttpPost]
        [Route("api/Account/login")]
        public async Task<IHttpActionResult> LoginAsync(UserLoginDto dto)
        {
            if (ModelState.IsValid)
            {
                var user = await PersonService.LoginAsync(dto.LoginName, dto.Password);
                if (user != null)
                {
                    var currentUser = new UserInfoDto();
                    currentUser.Id = user.Id;
                    currentUser.Name = user.Name;
                    currentUser.RolesId = string.Join(",", user.SysRoles.Select(c => c.Id).ToArray());

                    var token = JWTHelper.GetToken(currentUser);
                    return Json(new CommonResult("登录成功", token));
                }
                return Json(new CommonResult("账号密码错误", null, 200, false));
            }
            return Json(new CommonResult("验证错误", null, 400, false));
        }
    }
}
